import React, {PureComponent} from "react"
import {Input, Select} from "antd"
import update from "immutability-helper"

export default class FlowInput extends PureComponent {

  constructor(props) {
    super(props)
    this.state = {
      unit: 1024,
      kb: this.props.value,
    }
  }

  onSelectChange = (value) => {
    this.setState(update(this.state, {unit: {$set: value}}))
  }

  onChangeProxy = (onChange) => (e) => {
    this.setState(update(this.state, {kb: {$set: e.target.value * this.state.unit}}))
    if (onChange) onChange(e.target.value * this.state.unit)
  }

  render() {

    const {value, onChange, ...other} = this.props

    return <Input onChange={this.onChangeProxy(onChange)} value={this.state.kb / this.state.unit} {...other}
                  addonAfter={
                    <Select onChange={this.onSelectChange} value={this.state.unit}>
                      <Select.Option value={1024}>MB</Select.Option>
                      <Select.Option value={1024 * 1024}>GB</Select.Option>
                      <Select.Option value={1024 * 1024 * 1024}>TB</Select.Option>
                    </Select>
                  }/>
  }
}